import os
from openai import OpenAI
import time

os.environ['DASHSCOPE_API_KEY'] = "sk-3b8a5b48191b4399b246f872b2b4ef90"

def test_qwen(url="https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"):
    '''
    参考链接：https://bailian.console.aliyun.com/?spm=5176.29619931.J__Z58Z6CX7MY__Ll8p1ZOR.1.74cd59fcNdGpry#/model-market/detail/qwen-vl-plus
    {
        "id": "chatcmpl-c909ea3b-9ac7-9ec7-8d44-ad84f7bb8f31",
        "choices": [
            {
                "finish_reason": "stop",
                "index": 0,
                "logprobs": null,
                "message": {
                    "content": "这张图片显示了一位女士和一只狗在海滩上互动。她们似乎正在享受彼此的陪伴，狗狗坐在沙滩上伸出爪子与这位女士握手或玩耍。\n\n背景中可以看到海浪拍打着海岸线，并且有日落时分柔和光线照射下的天空。这给人一种宁静而温馨的感觉，可能是在傍晚或者清晨的时候拍摄的照片。这种场景通常象征着友谊、爱以及人与宠物之间的深厚情感连接。",
                    "refusal": null,
                    "role": "assistant",
                    "function_call": null,
                    "tool_calls": null
                }
            }
        ],
        "created": 1737349885,
        "model": "qwen-vl-plus",
        "object": "chat.completion",
        "service_tier": null,
        "system_fingerprint": null,
        "usage": {
            "completion_tokens": 92,
            "prompt_tokens": 1275,
            "total_tokens": 1367
        }
    }
    '''
    client = OpenAI(
        # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key="sk-xxx",
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    )
    completion = client.chat.completions.create(
        model="qwen-vl-plus",
        messages=[{"role": "user","content": [
                {"type": "text","text": "图中是什么样的场景"},
                {"type": "image_url",
                "image_url": {"url": url}}
                ]}]
        )
    print(completion.model_dump_json())
    '''
    {"id":"chatcmpl-d774d702-9502-97da-92a8-3ef6bfc7353c","choices":[{"finish_reason":"stop","index":0,"logprobs":null,"message":{"content":"这张照片显示的是一个办公室环境。在前景，有一个白色的办公桌或服务台区域，上面放着一台打印机和一些文件和其他物品。旁边还有一个灰色的碎纸机。\n\n背景中有几个隔间门，这表明这是一个开放式布局或者共享空间。地板是深色地毯覆盖的，并且可以看到一扇窗户透出自然光进来。整体上给人一种现代、干净的工作场所的感觉。","refusal":null,"role":"assistant","function_call":null,"tool_calls":null}}],"created":1737609862,"model":"qwen-vl-plus","object":"chat.completion","service_tier":null,"system_fingerprint":null,"usage":{"completion_tokens":85,"prompt_tokens":691,"total_tokens":776}}
    '''


def test_minio():
    from minio import Minio
    from minio.error import S3Error
    from datetime import timedelta

    # MinIO 服务的配置
    minio_url = "http://passk.chchy.vip:19013"
    access_key = "BglrQkwe6NFpiC7SAONk"
    secret_key = "6LwBnBB61KQ5CNkwYDSPlPOxvZQkSVIxE84953hB"

    # 初始化 MinIO 客户端
    client = Minio(
        endpoint=minio_url.replace("http://", "").replace("https://", ""),
        access_key=access_key,
        secret_key=secret_key,
        secure=False  # 如果使用 HTTPS，设置为 True
    )

    try:
        # 创建存储桶
        bucket_name = "qwen-bucket"
        if not client.bucket_exists(bucket_name):
            client.make_bucket(bucket_name)
            print(f"Bucket '{bucket_name}' created successfully!")
        else:
            print(f"Bucket '{bucket_name}' already exists.")

        # 上传文件
        file_path = "D:\DownloadFiles\微信图片_20240809172540.jpg"
        object_name = "20240809172540.jpg"
        client.fput_object(bucket_name, object_name, file_path)
        print(f"File '{file_path}' uploaded to bucket '{bucket_name}' as '{object_name}'.")

        # 列出存储桶中的对象
        print(f"Objects in bucket '{bucket_name}':")
        for obj in client.list_objects(bucket_name):
            print(f" - {obj.object_name}")


        url = client.presigned_get_object(bucket_name, object_name, expires=timedelta(seconds=60))
        print("preview url:", url)
        time.sleep(1)
        test_qwen(url)

        # 下载文件
        download_path = "D:/test/微信图片_20240809172540.jpg"
        client.fget_object(bucket_name, object_name, download_path)
        print(f"File '{object_name}' downloaded to '{download_path}'.")

    except S3Error as e:
        print(f"An error occurred: {e}")



if __name__ == "__main__":
    # test_qwen()
    test_minio()